package com.leetcode.binarytree;

/**
 * date:
 * description:
 */
public class Codec {
    private StringBuilder res;
    private int index;

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        // DFS前序遍历
        res = new StringBuilder();
        rserialize(root);
        // 删除末尾的逗号
        return res.deleteCharAt(res.length() - 1).toString();
    }

    public void rserialize(TreeNode root){
        if(root == null){
            res.append("null,");
        }else{
            res.append(root.val).append(",");
            rserialize(root.left);
            rserialize(root.right);
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        index = 0;
        String[] nodes = data.split(",");
        return rdeserialize(nodes);
    }

    public TreeNode rdeserialize(String[] nodes){
        if("null".equals(nodes[index])){
            index++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(nodes[index]));
        index++;
        root.left = rdeserialize(nodes);
        root.right = rdeserialize(nodes);
        return root;
    }

    public static void main(String[] args) {
        String root = "1,2,null,null,3,4,null,null,5,null,null";
        Codec codec = new Codec();
        TreeNode rootn = codec.deserialize(root);
        System.out.println(rootn.val + " " + rootn.left.val + " " + rootn.right.val);
    }
}
